package cct.smartmatrix.advertisement.service;

import cct.smartmatrix.advertisement.domain.User;
import cct.smartmatrix.advertisement.repository.UserRepository;
import cct.smartmatrix.advertisement.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 广告系统用户信息
 * Created by feng yingsheng on 7/18/2017.
 */
@Slf4j
@Service("userService")
public class UserService {

    @Value("${profile}")
    String profile;

    @Autowired
    UserRepository userRepository;

    /**
     * 初始化用户（系统中存在中城旅游网用户ID, 则加载用户信息，没有则注册基本信息，并加载用户信息）
     * @param zcUserId 中城旅游网用户ID
     * @return
     */
    public Map<Object, Object> initUser(String zcUserId) {
        log.info(profile);
        User user = userRepository.findOne(zcUserId);
        if(user == null) {
            user = new User(zcUserId, UUID.randomUUID().toString(), JWTUtils.SignJWT(zcUserId));
            long time = System.currentTimeMillis();
            user.setCreate_time(time);
            user.setUpdate_time(time);
            User myUser = userRepository.save(user);
            log.info("register an new user=" + myUser.getAdUserId());
        }
        else {
            String token = user.getToken();
            //无token或者过期
            if(StringUtils.isEmpty(token) || "-1".equalsIgnoreCase(JWTUtils.verifyJWT(token))) {
                user.setToken(JWTUtils.SignJWT(zcUserId));
                user.setUpdate_time(System.currentTimeMillis());
                userRepository.save(user);
            }
            log.info("zcUserId=" + zcUserId + ", find user=" + user.getAdUserId());
        }

        Map<Object, Object> map = new HashMap<>();
        map.put("code", "0");
        map.put("msg", "success");
        Map<Object, Object> data = new HashMap<>();
        data.put("zcUserId", user.getZcUserId());
        data.put("adUserId", user.getAdUserId());
        data.put("token", user.getToken());
        map.put("data", data);
        return map;
    }
}
